import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Activity, ActivityType, MoodConfig, Settings } from '@/types';

interface AppStore {
  // 状态
  activities: Activity[];
  settings: Settings;
  currentCoins: number;
  
  // 添加事项相关
  addActivity: (activity: Omit<Activity, 'id' | 'createdAt' | 'updatedAt'>) => void;
  updateActivity: (id: string, updates: Partial<Activity>) => void;
  deleteActivity: (id: string) => void;
  
  // 设置相关
  addActivityType: (activityType: Omit<ActivityType, 'id'>) => void;
  updateActivityType: (id: string, updates: Partial<ActivityType>) => void;
  deleteActivityType: (id: string) => void;
  
  addMoodConfig: (mood: Omit<MoodConfig, 'id'>) => void;
  updateMoodConfig: (id: string, updates: Partial<MoodConfig>) => void;
  deleteMoodConfig: (id: string) => void;
  
  // 金币相关
  addCoins: (amount: number) => void;
  updateTotalCoins: (amount: number) => void;
  
  // 查询相关
  getActivitiesByDate: (date: Date) => Activity[];
  getActivitiesByMood: (mood: string) => Activity[];
  getActivitiesByType: (type: string) => Activity[];
  getCoinAnalysis: () => any;
  getMoodDistribution: () => any;
}

const defaultMoods: MoodConfig[] = [
  { id: '1', name: '开心', emoji: '😊', coinModifier: 5, color: '#10B981' },
  { id: '2', name: '一般', emoji: '😐', coinModifier: 0, color: '#6B7280' },
  { id: '3', name: '不安焦虑', emoji: '😰', coinModifier: -3, color: '#EF4444' },
  { id: '4', name: '平静', emoji: '😌', coinModifier: 3, color: '#3B82F6' },
  { id: '5', name: '兴奋', emoji: '🤩', coinModifier: 8, color: '#F59E0B' },
  { id: '6', name: '疲惫', emoji: '😴', coinModifier: -2, color: '#8B5CF6' },
];

const defaultActivityTypes: ActivityType[] = [
  { id: '1', name: '阅读', coinValue: 10, color: '#10B981', icon: '📚' },
  { id: '2', name: '运动', coinValue: 15, color: '#3B82F6', icon: '🏃‍♂️' },
  { id: '3', name: '学习', coinValue: 20, color: '#8B5CF6', icon: '📖' },
  { id: '4', name: '工作', coinValue: 25, color: '#F59E0B', icon: '💼' },
  { id: '5', name: '刷短视频', coinValue: -5, color: '#EF4444', icon: '📱' },
  { id: '6', name: '熬夜', coinValue: -10, color: '#EF4444', icon: '🌙' },
];

export const useAppStore = create<AppStore>()(
  persist(
    (set, get) => ({
      // 初始状态
      activities: [],
      currentCoins: 0,
      settings: {
        totalCoins: 0,
        activityTypes: defaultActivityTypes,
        moodConfigs: defaultMoods,
        defaultMoods,
      },

      // 添加事项
      addActivity: (activityData) => {
        const id = Date.now().toString();
        const activity: Activity = {
          ...activityData,
          id,
          createdAt: new Date(),
          updatedAt: new Date(),
        };
        
        set((state) => {
          const newTotalCoins = state.currentCoins + activity.coinChange;
          return {
            activities: [activity, ...state.activities],
            currentCoins: Math.max(0, newTotalCoins),
            settings: {
              ...state.settings,
              totalCoins: Math.max(0, newTotalCoins),
            },
          };
        });
      },

      updateActivity: (id, updates) => {
        set((state) => ({
          activities: state.activities.map(activity => 
            activity.id === id 
              ? { ...activity, ...updates, updatedAt: new Date() }
              : activity
          )
        }));
      },

      deleteActivity: (id) => {
        set((state) => {
          const activity = state.activities.find(a => a.id === id);
          if (!activity) return state;
          
          return {
            activities: state.activities.filter(a => a.id !== id),
            // 如果删除的活动有金币变化，需要相应调整当前金币
            currentCoins: state.currentCoins - (activity.coinChange || 0),
          };
        });
      },

      // 设置相关
      addActivityType: (activityTypeData) => {
        const id = Date.now().toString();
        const activityType: ActivityType = { ...activityTypeData, id };
        
        set((state) => ({
          settings: {
            ...state.settings,
            activityTypes: [...state.settings.activityTypes, activityType],
          },
        }));
      },

      updateActivityType: (id, updates) => {
        set((state) => ({
          settings: {
            ...state.settings,
            activityTypes: state.settings.activityTypes.map(type =>
              type.id === id ? { ...type, ...updates } : type
            ),
          },
        }));
      },

      deleteActivityType: (id) => {
        set((state) => ({
          settings: {
            ...state.settings,
            activityTypes: state.settings.activityTypes.filter(type => type.id !== id),
          },
        }));
      },

      addMoodConfig: (moodData) => {
        const id = Date.now().toString();
        const mood: MoodConfig = { ...moodData, id };
        
        set((state) => ({
          settings: {
            ...state.settings,
            moodConfigs: [...state.settings.moodConfigs, mood],
          },
        }));
      },

      updateMoodConfig: (id, updates) => {
        set((state) => ({
          settings: {
            ...state.settings,
            moodConfigs: state.settings.moodConfigs.map(mood =>
              mood.id === id ? { ...mood, ...updates } : mood
            ),
          },
        }));
      },

      deleteMoodConfig: (id) => {
        set((state) => ({
          settings: {
            ...state.settings,
            moodConfigs: state.settings.moodConfigs.filter(mood => mood.id !== id),
          },
        }));
      },

      // 金币相关
      addCoins: (amount) => {
        set((state) => {
          const newTotal = Math.max(0, state.currentCoins + amount);
          return {
            currentCoins: newTotal,
            settings: {
              ...state.settings,
              totalCoins: newTotal,
            },
          };
        });
      },

      updateTotalCoins: (amount) => {
        set((state) => ({
          currentCoins: Math.max(0, amount),
          settings: {
            ...state.settings,
            totalCoins: Math.max(0, amount),
          },
        }));
      },

      // 查询相关
      getActivitiesByDate: (date) => {
        const state = get();
        const targetDate = new Date(date);
        return state.activities.filter(activity => {
          const activityDate = new Date(activity.timestamp);
          return (
            activityDate.getFullYear() === targetDate.getFullYear() &&
            activityDate.getMonth() === targetDate.getMonth() &&
            activityDate.getDate() === targetDate.getDate()
          );
        });
      },

      getActivitiesByMood: (mood) => {
        const state = get();
        return state.activities.filter(activity => activity.mood === mood);
      },

      getActivitiesByType: (type) => {
        const state = get();
        return state.activities.filter(activity => activity.activityType === type);
      },

      getCoinAnalysis: () => {
        const state = get();
        const income: any[] = [];
        const expenses: any[] = [];
        
        // 按事项类型分析
        const typeAnalysis = new Map();
        state.activities.forEach(activity => {
          const key = activity.activityType;
          if (!typeAnalysis.has(key)) {
            typeAnalysis.set(key, { income: 0, expense: 0, count: 0 });
          }
          const analysis = typeAnalysis.get(key);
          if (activity.coinChange > 0) {
            analysis.income += activity.coinChange;
          } else {
            analysis.expense += Math.abs(activity.coinChange);
          }
          analysis.count += 1;
        });

        // 转换为数组格式
        typeAnalysis.forEach((data, type) => {
          const activityType = state.settings.activityTypes.find(t => t.name === type);
          if (data.income > 0) {
            income.push({
              source: type,
              amount: data.income,
              count: data.count,
              color: activityType?.color || '#10B981',
              type: 'income' as const
            });
          }
          if (data.expense > 0) {
            expenses.push({
              source: type,
              amount: data.expense,
              count: data.count,
              color: activityType?.color || '#EF4444',
              type: 'expense' as const
            });
          }
        });

        return { income, expenses };
      },

      getMoodDistribution: () => {
        const state = get();
        const moodCounts = new Map();
        
        state.activities.forEach(activity => {
          const mood = activity.mood;
          moodCounts.set(mood, (moodCounts.get(mood) || 0) + 1);
        });

        const total = state.activities.length;
        const distribution: any[] = [];

        moodCounts.forEach((count, moodName) => {
          const moodConfig = state.settings.moodConfigs.find(m => m.name === moodName);
          distribution.push({
            moodName,
            moodEmoji: moodConfig?.emoji || '😐',
            count,
            percentage: total > 0 ? (count / total) * 100 : 0,
            color: moodConfig?.color || '#6B7280'
          });
        });

        return distribution.sort((a, b) => b.count - a.count);
      },
    }),
    {
      name: 'attention-coin-storage',
    }
  )
);